﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Drawing.Imaging;

namespace KingSite.Library.Tools {

    /// <summary>
    /// HttpPost增强类
    /// </summary>
    public class HttpPostUtil {
        string _boundary = "------HttpPostData";
        string _url;
        byte[] bs = new byte[0];

        public HttpPostUtil(string url) {
            this._url = url;
        }

        public byte[] Send() {
            WebClient myWebClient = new WebClient();
            myWebClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + _boundary);
            EndData();
            return myWebClient.UploadData(_url, bs);
        }

        public void ClearData() {
            Array.Clear(bs, 0, bs.Length);
        }

        public void AddTextParameter(string name, string value) {
            StringBuilder s = new StringBuilder();
            s.Append("--").Append(_boundary).Append("\r\n");
            s.Append("Content-Disposition:  form-data;  name=\"" + name + "\"\r\n");
            s.Append("\r\n");
            s.Append(value).Append("\r\n");
            AppendString(s.ToString());
        }

        public void AddFileParameter(string name, FileInfo file) {
            StringBuilder s = new StringBuilder();
            s.Append("--").Append(_boundary).Append("\r\n");
            s.Append("Content-Disposition:  form-data;  name=\"" + name + "\";  filename=\"" + file.Name + "\"\r\n");
            s.Append("Content-Type: " + GetContentType(file) + "\r\n");
            s.Append("\r\n");
            AppendString(s.ToString());
            AppendBytes(GetFileBytes(file));
            AppendString("\r\n");
        }

        byte[] GetFileBytes(FileInfo f) {
            FileStream fs = new FileStream(f.FullName, FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            byte[] b = br.ReadBytes((int)f.Length);
            br.Close();
            fs.Close();
            return b;
        }

        public virtual string GetContentType(FileInfo f) {
            return "application/octet-stream"; 
        }


        void AppendBytes(byte[] bytes) {
            byte[] newByte = new byte[bs.Length + bytes.Length];
            Array.Copy(bs, 0, newByte, 0, bs.Length);
            Array.Copy(bytes, 0, newByte, bs.Length, bytes.Length);
            bs = newByte;
        }

        void AppendString(string value) {
            byte[] bytes = Encoding.UTF8.GetBytes(value);
            AppendBytes(bytes);
        }

        void EndData() {
            StringBuilder s = new StringBuilder();
            s.Append("--").Append(_boundary).Append("--\r\n");
            s.Append("\r\n");
            AppendString(s.ToString());
        }
    }

}
